package com.kbt.net;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 泛型类型的Request，T的类型是bean 这个地方解析数据的时候使用Gson，注意返回的Json字段名字一定要和Bean的字段对应起来 Created
 * by zhang_q
 */
public class PostRequest<T> extends Request<T> {
    /**
     * 监听器
     */
    private final Listener<T> listener;

    /**
     * 解析方式
     */
    private Gson mGson;

    /**
     * 解析的Bean类型
     */
    private Class<T> clazz;


    /**
     * params
     */
    private Map<String, String> params = new HashMap<String, String>();

    /**
     * 初始化的类型(Post请求)（mRequestBody是转换成JsonString的字符串）
     */
    public PostRequest(int method, String url, Map<String, String>params,
                       Class<T> clazz, Listener<T> listener, ErrorListener errorListener) {
        super(method, url, errorListener);
        mGson = new Gson();
        this.clazz = clazz;
        this.listener = listener;
        this.params = params;
    }

    /**
     * 初始化的类型(post请求)
     */
    public PostRequest(String url, Class<T> clazz, Listener<T> listener, ErrorListener errorListener) {
        this(Method.GET, url, null, clazz, listener, errorListener);
    }


    @Override
    protected void deliverResponse(T t) {
        listener.onResponse(t);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String strObject = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            T parsedGSON = mGson.fromJson(strObject, clazz);
            return Response.success(parsedGSON,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (Exception e) {
            Log.e("error", e.getMessage().toString());
            return Response.error(new ParseError(e));
        }
    }
    @Override
    protected Map<String, String> getParams() {
        //在这里设置需要post的参数
        return params;
    }

}
